package cn.kgc.service.impl;

import cn.kgc.client.SmsSpuFeignClient;
import cn.kgc.client.WmsWareSkuFeignClient;
import cn.kgc.commons.config.ThreadPoolConfig;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.vo.Result;
import cn.kgc.constant.PmsSpuDefaultImage;
import cn.kgc.constant.PmsSpuStatus;
import cn.kgc.dto.*;
import cn.kgc.dto.add.*;
import cn.kgc.entity.*;
import cn.kgc.mapper.*;
import com.alibaba.druid.sql.visitor.functions.Concat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.service.PmsSpuInfoService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * spu信息(PmsSpuInfo)表服务实现类
 *
 * @author 石浩杰
 * @since 2022-12-05 09:38:35
 */
@Service("pmsSpuInfoService")
@Slf4j
public class PmsSpuInfoServiceImpl extends ServiceImpl<PmsSpuInfoMapper, PmsSpuInfo> implements PmsSpuInfoService {
    @Resource
    private PmsSpuInfoMapper pmsSpuInfoMapper;

    @Resource
    private PmsSpuInfoDescMapper pmsSpuInfoDescMapper;

    @Resource
    private PmsSpuImagesMapper pmsSpuImagesMapper;

    @Resource
    private PmsAttrMapper pmsAttrMapper;

    @Resource
    private PmsSkuInfoMapper pmsSkuInfoMapper;

    @Resource
    private PmsSkuImagesMapper pmsSkuImagesMapper;

    @Resource
    private PmsSkuSaleAttrValueMapper  pmsSkuSaleAttrValueMapper;

    @Resource
    private PmsProductAttrValueMapper pmsProductAttrValueMapper;

    @Resource
    private SmsSpuFeignClient smsSpuFeignClient;

    @Resource
    private PmsBrandMapper pmsBrandMapper;

    @Resource
    private WmsWareSkuFeignClient wmsWareSkuFeignClient;

    @Resource
    private SkuEsModelElasticsearchRepository skuEsModelElasticsearchRepository;

    @Resource
    private PmsCategoryMapper pmsCategoryMapper;
    
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private PmsAttrGroupMapper pmsAttrGroupMapper;

    @Resource
    private PmsAttrAttrgroupRelationMapper pmsAttrAttrgroupRelationMapper;

    @Override
    public SpuItemVO selectById(Long skuId){

        SpuItemVO spuItemVO=new SpuItemVO();
        //商品的基本信息(skuInfo)
        CompletableFuture<PmsSkuInfo> pmsSkuInfoCompleableFuture=CompletableFuture.supplyAsync(()->{
            PmsSkuInfo pmsSkuInfo = pmsSkuInfoMapper.selectById(skuId);
            if (pmsSkuInfo==null){
                throw new HttpException(20007,HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
            
            Long brandId=pmsSkuInfo.getBrandId();
            PmsBrand pmsBrand=pmsBrandMapper.selectById(brandId);
            pmsSkuInfo.setBrandName(pmsBrand.getName());
            
            Long cateLogId=pmsSkuInfo.getCatalogId();
            PmsCategory pmsCategory=pmsCategoryMapper.selectById(cateLogId);
            pmsSkuInfo.setCategoryName(pmsCategory.getName());
            
            Long spuId=pmsSkuInfo.getSpuId();
            PmsSpuInfo pmsSpuInfo=pmsSpuInfoMapper.selectById(spuId);
            pmsSkuInfo.setSpuName(pmsSpuInfo.getSpuName());

            spuItemVO.setPmsSkuInfo(pmsSkuInfo);
            return pmsSkuInfo;
        }, threadPoolExecutor);
        //商品的图片信息
        CompletableFuture<Void> pmsSkuInmagesCompletableFuture = CompletableFuture.runAsync(() -> {
            LambdaQueryWrapper<PmsSkuImages> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmsSkuImages::getSkuId, skuId);
            List<PmsSkuImages> pmsSkuImagesList = pmsSkuImagesMapper.selectList(lambdaQueryWrapper);
            spuItemVO.setImagesList(pmsSkuImagesList);
        }, threadPoolExecutor);
        //商品的销售属性
        CompletableFuture<Void> pmsSkuSaleAttrValueCompletableFuture = CompletableFuture.runAsync(() -> {
            LambdaQueryWrapper<PmsSkuSaleAttrValue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmsSkuSaleAttrValue::getSkuId, skuId);
            List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValueList = pmsSkuSaleAttrValueMapper.selectList(lambdaQueryWrapper);
            List<Attr> attrList = pmsSkuSaleAttrValueList.stream().map(pmsSkuSaleAttrValue -> {
                Attr attr = new Attr();
                BeanUtils.copyProperties(pmsSkuSaleAttrValue, attr);
                return attr;
            }).collect(Collectors.toList());
            spuItemVO.setPmsSkuItemSaleAttrVoList(attrList);
        }, threadPoolExecutor);

        //获取SPU的介绍信息
        CompletableFuture<Void> pmsSkuInfoDescCompletableFuture = pmsSkuInfoCompleableFuture.thenAcceptAsync(skuInfo -> {
            Long spuId = skuInfo.getSpuId();
            PmsSpuInfoDesc pmsSpuInfoDesc = pmsSpuInfoDescMapper.selectById(spuId);
            spuItemVO.setPmsSpuInfoDesc(pmsSpuInfoDesc);
        });
        //查询属性组的信息
        CompletableFuture<Void> pmsAttrGroupCompletableFuture = pmsSkuInfoCompleableFuture.thenAcceptAsync(skuInfo->{
            //商品基本信息对应的分类的id
            Long catalogId = skuInfo.getCatalogId();
            //最终商品对应的属性组的集合
            List<SpuItemVO.PmsSpuItemGroupAttrVo> pmsSpuItemGroupAttrVoList=new ArrayList<>();
            //根据商品分类的id查询属性组的信息
            LambdaQueryWrapper<PmsAttrGroup> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmsAttrGroup::getCatelogId,catalogId);
            List<PmsAttrGroup> pmsAttrGroupList=pmsAttrGroupMapper.selectList(lambdaQueryWrapper);
            for (PmsAttrGroup pmsAttrGroup : pmsAttrGroupList) {
                SpuItemVO.PmsSpuItemGroupAttrVo pmsSpuItemGroupAttrVo=new SpuItemVO.PmsSpuItemGroupAttrVo();
                //获得属性组的名字
                String attrGroupName = pmsAttrGroup.getAttrGroupName();
                pmsSpuItemGroupAttrVo.setGroupName(attrGroupName);
                //获得属性组的基本属性的信息
                //1 通过属性组的id获得属性组与属性关联关系的集合
                Long attrGroupId = pmsAttrGroup.getId();
                LambdaQueryWrapper<PmsAttrAttrgroupRelation> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(PmsAttrAttrgroupRelation::getAttrGroupId,attrGroupId);
                List<PmsAttrAttrgroupRelation> pmsAttrAttrgroupRelationList = pmsAttrAttrgroupRelationMapper.selectList(lambdaQueryWrapper2);
                //属性组对应的基本属性集合
                List<Attr> baseAttrList=new ArrayList<>();
                //2 通过属性组与属性关联关系的集合获得关联属性的id获得属性锁对应的属性的集合
                for (PmsAttrAttrgroupRelation pmsAttrAttrgroupRelation : pmsAttrAttrgroupRelationList) {
                    Long attrId = pmsAttrAttrgroupRelation.getAttrId();
                    //3 通过属性的id和商品的id去商品属性表中获得基本属性信息
                    LambdaQueryWrapper<PmsProductAttrValue> lambdaQueryWrapper3=new LambdaQueryWrapper<>();
                    lambdaQueryWrapper3.eq(PmsProductAttrValue::getAttrId,attrId);
                    skuInfo.getSpuId();
                    lambdaQueryWrapper3.eq(PmsProductAttrValue::getSpuId,skuInfo.getSpuId());
                    PmsProductAttrValue pmsProductAttrValue=pmsProductAttrValueMapper.selectOne(lambdaQueryWrapper3);
                    Attr attr=new Attr();
                    BeanUtils.copyProperties(pmsProductAttrValue,attr);
                    baseAttrList.add(attr);
                }
                pmsSpuItemGroupAttrVo.setBaseAttrs(baseAttrList);
                pmsSpuItemGroupAttrVoList.add(pmsSpuItemGroupAttrVo);
            }
            spuItemVO.setPmsSpuItemGroupAttrVo(pmsSpuItemGroupAttrVoList);
        },threadPoolExecutor);
        //等待所有的异步任务执行完毕以后，再向下执行
        CompletableFuture.allOf(
                pmsSkuInfoDescCompletableFuture,
                pmsAttrGroupCompletableFuture,
                pmsSkuInmagesCompletableFuture,
                pmsSkuSaleAttrValueCompletableFuture
        ).join();
        return spuItemVO;
    }

    @Override
    @GlobalTransactional
    public boolean savePmsSpuInfo(SpuInfoVO spuInfoVO) {
        //保存商品spu信息
        PmsSpuInfo pmsSpuInfo = new PmsSpuInfo();
        BeanUtils.copyProperties(spuInfoVO, pmsSpuInfo);
        pmsSpuInfoMapper.insert(pmsSpuInfo);
        //商品描述信息
        List<String> decriptList=spuInfoVO.getDecript();
        PmsSpuInfoDesc pmsSpuInfoDesc = new PmsSpuInfoDesc();
        pmsSpuInfoDesc.setId(pmsSpuInfo.getId());
        String desc="";
        for (String s : decriptList) {
            desc+=s+";";
        }
        pmsSpuInfoDesc.setDecript(desc);
        pmsSpuInfoDescMapper.insert(pmsSpuInfoDesc);
        //商品图片信息
        List<String> imageList=spuInfoVO.getImages();
        int count=0;
        for (String s : imageList){
            PmsSpuImages pmsSpuImages = new PmsSpuImages();
            if (count==0){
                pmsSpuImages.setDefaultImg(PmsSpuDefaultImage.DEFAULT_IMAGE.getDefaultImage());//是否是默认图片
            }
            pmsSpuImages.setSpuId(pmsSpuInfo.getId());
            pmsSpuImages.setImgUrl(s);
            pmsSpuImages.setImgName(s);
            pmsSpuImagesMapper.insert(pmsSpuImages);
            count++;
        }

        //商品基本属性
        List<BaseAttrs> baseAttrsList=spuInfoVO.getBaseAttrs();
        //新增的属性信息
        PmsProductAttrValue pmsProductAttrValue = new PmsProductAttrValue();
        for (BaseAttrs baseAttrs : baseAttrsList) {
            //基础属性的ID
            pmsProductAttrValue.setAttrId(baseAttrs.getAttrId());
            PmsAttr pmsAttr=pmsAttrMapper.selectById(baseAttrs.getAttrId());
            //基础属性的名字
            pmsProductAttrValue.setAttrName(pmsAttr.getAttrName());
            //基础属性的值
            pmsProductAttrValue.setAttrValue(baseAttrs.getAttrValues());
            //基础属性的排序规则
            pmsProductAttrValue.setAttrSort(baseAttrs.getShowDesc());
            //基础属性对应的商品id
            pmsProductAttrValue.setSpuId(pmsSpuInfo.getId());
            //基础属性的快速展示
            pmsProductAttrValue.setQuickShow(baseAttrs.getQuickShow());
            pmsProductAttrValueMapper.insert(pmsProductAttrValue);
        }
        //商品sku信息
        //新增商品的sku信息
        List<Skus> skusList=spuInfoVO.getSkus();
        PmsSkuInfo pmsSkuInfo = new PmsSkuInfo();
        //商品sku图片信息
        PmsSkuImages pmsSkuImages = new PmsSkuImages();
        //商品销售属性
        PmsSkuSaleAttrValue pmsSkuSaleAttrValue = new PmsSkuSaleAttrValue();
        //sku会员的价格
        List<SmsMemberPriceAddDTO> smsMemberPriceAddDTOList = new ArrayList<>();
        //sku打折信息
        List<SmsSkuLadderAddDTO> smsSkuLadderAddDTOList = new ArrayList<>();
        //sku满减信息
        List<SmsSkuFullReductionAddDTO> smsSkuFullReductionAddDTOList = new ArrayList<>();
        for (Skus skus : skusList) {
            pmsSkuInfo.setBrandId(spuInfoVO.getBrandId());
            pmsSkuInfo.setCatalogId(spuInfoVO.getCatalogId());
            pmsSkuInfo.setPrice(skus.getPrice());
            pmsSkuInfo.setSaleCount(0L);
            if (count==0){
                pmsSkuInfo.setSkuDefaultImg(skus.getImages().get(0));
            }
            pmsSkuInfo.setSkuDesc("");
            pmsSkuInfo.setSkuName(skus.getSkuName());
            pmsSkuInfo.setSkuSubtitle(skus.getSkuSubtitle());
            pmsSkuInfo.setSkuTitle(skus.getSkuTitle());
            pmsSkuInfo.setSpuId(pmsSpuInfo.getId());
            pmsSkuInfoMapper.insert(pmsSkuInfo);
            //新增商品的sku图片信息
            List<String> imagesList=skus.getImages();
            int index=0;
            for (String s : imagesList) {
                if (index==0){
                    pmsSkuImages.setDefaultImg(1);
                }
                pmsSkuImages.setImgUrl(s);
                pmsSkuImages.setImgSort(0);
                pmsSkuImages.setSkuId(pmsSkuInfo.getId());
                pmsSkuImagesMapper.insert(pmsSkuImages);
                index++;
            }
            //获得商品销售属性
            List<Attr> saleAttrsList=skus.getAttr();
            for (Attr attr : saleAttrsList) {
                pmsSkuSaleAttrValue.setAttrId(attr.getAttrId());
                pmsSkuSaleAttrValue.setAttrName(attr.getAttrName());
                pmsSkuSaleAttrValue.setAttrValue(attr.getAttrValue());
                pmsSkuSaleAttrValue.setAttrSort(0);
                pmsSkuSaleAttrValue.setSkuId(pmsSkuInfo.getId());
                pmsSkuSaleAttrValueMapper.insert(pmsSkuSaleAttrValue);
            }
            count++;
            //获得每个sku的会员价格
            List<MemberPrice> memberPriceList=skus.getMemberPrice();

            for (MemberPrice memberPrice : memberPriceList) {
                SmsMemberPriceAddDTO smsMemberPriceAddDTO = new SmsMemberPriceAddDTO();
                smsMemberPriceAddDTO.setAddOther((short)0);
                smsMemberPriceAddDTO.setMemberLevelId(memberPrice.getId());
                smsMemberPriceAddDTO.setMemberLevelName(memberPrice.getName());
                smsMemberPriceAddDTO.setMemberPrice(memberPrice.getPrice());
                smsMemberPriceAddDTO.setSkuId(pmsSkuInfo.getId());
                smsMemberPriceAddDTOList.add(smsMemberPriceAddDTO);
            }
            //获得每个sku的打折信息
            SmsSkuLadderAddDTO smsSkuLadderAddDTO = new SmsSkuLadderAddDTO();
            smsSkuLadderAddDTO.setAddOther((short)0);
            smsSkuLadderAddDTO.setDiscount(skus.getDiscount());
            smsSkuLadderAddDTO.setFullCount(skus.getFullCount());
            smsSkuLadderAddDTO.setPrice(skus.getPrice());
            smsSkuLadderAddDTO.setSkuId(pmsSkuInfo.getId());
            //保存到打折信息的集合中
            smsSkuLadderAddDTOList.add(smsSkuLadderAddDTO);
            //每个sku的满减信息
            SmsSkuFullReductionAddDTO smsSkuFullReductionAddDTO = new SmsSkuFullReductionAddDTO();
            smsSkuFullReductionAddDTO.setAddOther((short)0);
            smsSkuFullReductionAddDTO.setFullPrice(skus.getFullPrice());
            smsSkuFullReductionAddDTO.setReducePrice(skus.getReducePrice());
            smsSkuFullReductionAddDTO.setSkuId(pmsSkuInfo.getId());
            smsSkuFullReductionAddDTOList.add(smsSkuFullReductionAddDTO);
        }
        //封装参数
        SmsSpuAddDTO smsSpuAddDTO = new SmsSpuAddDTO();
        //封装积分参数
        SmsSpuBoundsAddDTO smsSpuBoundsAddDTO = new SmsSpuBoundsAddDTO();
        //前段传入的积分信息
        Bounds bounds=spuInfoVO.getBounds();
        smsSpuBoundsAddDTO.setBuyBounds(bounds.getBuyBounds());
        smsSpuBoundsAddDTO.setGrowBounds(bounds.getGrowBounds());
        smsSpuBoundsAddDTO.setSpuId(pmsSpuInfo.getId());
        //商品的成长积分 购买积分
        smsSpuAddDTO.setSmsSpuBoundsAddDTO(smsSpuBoundsAddDTO);
        //商品的会员价格
        smsSpuAddDTO.setSmsMemberPriceAddDTOList(smsMemberPriceAddDTOList);
        //商品的折扣
        smsSpuAddDTO.setSmsSkuLadderAddDTOList(smsSkuLadderAddDTOList);
        //商品的满减
        smsSpuAddDTO.setSmsSkuFullReductionAddDTOList(smsSkuFullReductionAddDTOList);
        Result result=smsSpuFeignClient.saveSmsSpu(smsSpuAddDTO);
        if (result.getCode()== HttpStatus.INTERNAL_SERVER_ERROR.value()){
            throw new HttpException(20003,500);
        }
        return true;
    }

    /**
     * 实现商品的上下架功能
     * @param spuId 商品的id
     * @param status 商品要修改的状态
     */
    private void updateSpuStatus(long spuId,short status) {
        PmsSpuInfo pmsSpuInfo = pmsSpuInfoMapper.selectById(spuId);
        if(pmsSpuInfo==null){
            throw new HttpException(20005,HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        if(pmsSpuInfo.getPublishStatus()== status){ //修改状态和原有状态一样
            if (status==PmsSpuStatus.PUBLISH.getStatus()){
                throw new HttpException(20006,HttpStatus.INTERNAL_SERVER_ERROR.value());
            }else {
                throw new HttpException(20007,HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        }
        pmsSpuInfo.setPublishStatus(status);
        pmsSpuInfoMapper.updateById(pmsSpuInfo);
    }

    @Transactional
    public boolean up(long spuId) {
        log.info("商品上架:spuId:{}",spuId);
        //1 修改商品的状态 ，判断商品是否上架，如果没有上架，就上架
        updateSpuStatus(spuId,PmsSpuStatus.PUBLISH.getStatus());
        //2 收集商品对应的sku信息
        List<SkuEsModel> skuEsModelList = getSkuEsModel(spuId);
        //3 将SKU的信息发送给ES进行保存
        for (SkuEsModel skuEsModel : skuEsModelList) {
            skuEsModelElasticsearchRepository.save(skuEsModel);
        }
        return true;
    }

    private List<SkuEsModel> getSkuEsModel(long spuId) {
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        //1 查询当前spuId对应的所有sku信息
        LambdaQueryWrapper<PmsSkuInfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsSkuInfo::getSpuId,spuId);
        List<PmsSkuInfo> skuInfoList=pmsSkuInfoMapper.selectList(lambdaQueryWrapper);
        //每个sku对应的都是一个ES中的SkuEsModel对象
        for (PmsSkuInfo pmsSkuInfo : skuInfoList) {
            SkuEsModel skuEsModel = new SkuEsModel();//一个es对象
            skuEsModel.setSpuId(spuId);//spuId
            skuEsModel.setSkuId(pmsSkuInfo.getId());//skuId
            skuEsModel.setSubTitle(pmsSkuInfo.getSkuSubtitle());//二级标记
            skuEsModel.setSkuPrice(pmsSkuInfo.getPrice());//价格
            skuEsModel.setSkuImg(pmsSkuInfo.getSkuDefaultImg());//图片
            skuEsModel.setSaleCount(pmsSkuInfo.getSaleCount());//销量
            skuEsModel.setBrandId(pmsSkuInfo.getBrandId());//品牌id
            skuEsModel.setCategoryId(pmsSkuInfo.getCatalogId());//分类id
            PmsCategory pmsCategory=pmsCategoryMapper.selectById(pmsSkuInfo.getCatalogId());
            if (pmsCategory!=null){
                skuEsModel.setCategoryName(pmsCategory.getName());//分类名称
            }
            PmsBrand pmsBrand=pmsBrandMapper.selectById(pmsSkuInfo.getBrandId());
            if (pmsBrand!=null){
                //品牌名字
                skuEsModel.setBrandName(pmsBrand.getName());
                //品牌图片
                skuEsModel.setBrandImg(pmsBrand.getLogo());
            }
            getSkuAttrValue(pmsSkuInfo, skuEsModel);
            //是否还有库存
            boolean hasStock = wmsWareSkuFeignClient.hasStock(pmsSkuInfo.getId()).getData();
            skuEsModel.setHasStock(hasStock);
            skuEsModelList.add(skuEsModel);
        }
        return skuEsModelList;
    }

    private void getSkuAttrValue(PmsSkuInfo pmsSkuInfo, SkuEsModel skuEsModel) {
        //销售属性信息
        LambdaQueryWrapper<PmsSkuSaleAttrValue> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(PmsSkuSaleAttrValue::getSkuId, pmsSkuInfo.getId());
        List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValueList=pmsSkuSaleAttrValueMapper.selectList(lambdaQueryWrapper2);
        List<SkuEsModel.Attrs> attrList=new ArrayList<>();
        for (PmsSkuSaleAttrValue pmsSkuSaleAttrValue : pmsSkuSaleAttrValueList) {
            SkuEsModel.Attrs attr=new SkuEsModel.Attrs();
            BeanUtils.copyProperties(pmsSkuSaleAttrValue,attr);
            attrList.add(attr);
        }
        skuEsModel.setAttrList(attrList);
    }


    @Transactional
    public boolean down(long spuId) {
        return false;
    }
}
